//
//  SheZhiViewController.swift
//  ZHM
//
//  Created by zzddongge on 16/9/8.
//  Copyright © 2016年 zzd. All rights reserved.
//

/*
    关于协议传值,自己收获：
       1、当B向A传递数值时,这个时候A不希望B知道自己的一些东西,也就是说知道的越少越好.
       2、这个时候B是定义一个规则,让其它的ViewController来实现它,其它的它不管
    协议传值需要五个步骤：
       1、在B类中声明协议,例如：
            protocol SheZhiViewControllerDelegate:class {
                func chuanDiMoShiAndFenZhong(xuanZhongDeMoShiZhi:String,xuanZhongFenZhongZhi:String)
            }
       2、定义一个引用delegate,类型为声明的类型,例如：注意weak和？必须
            weak var delegate:SheZhiViewControllerDelegate?
       3、当用户点击按钮或者点击其他对象时,触发B发送消息给他的代理
            func wanChengSheZhi(){
                print("将用户选择的值传递到上一个页面,并返回到上一个页面")
                print(linShiMoShiChangedValue)
                print(inputValue)
                delegate?.chuanDiMoShiAndFenZhong(linShiMoShiChangedValue!,xuanZhongFenZhongZhi: inputValue!)
 
                self.navigationController?.popViewControllerAnimated(true)
            }

       4、对象A要遵守这个协议,需要在A类名称的后面追加该代理类型,并且实现该协议
            class XiaoJianPanXunLianViewController: UIViewController,SheZhiViewControllerDelegate
                
       5、告诉对象B,A是它的代理
            //该方法跳转到设置界面
            func tiaoZhuanZhiSheZhiXuanXiang(){
                let sheZhiViewController = SheZhiViewController()
                sheZhiViewController.delegate = self
                self.navigationController?.pushViewController(sheZhiViewController, animated: true)
            }

 */
import UIKit

protocol SheZhiViewControllerDelegate:class {
    func chuanDiMoShiAndFenZhong(_ xuanZhongDeMoShiZhi:String,xuanZhongFenZhongZhi:String)
}

class SheZhiViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UITextViewDelegate {

    weak var delegate:SheZhiViewControllerDelegate?

    let screenWidth = UIScreen.main.bounds.width
    let screenHeight = UIScreen.main.bounds.height
    
    var moShiLeiBieTableView:UITableView?
    
    var moShiItems:[String] = ["计时模式","定时模式"]
    
    var sheZhiMoShiAndTimeArray:[MoShiSheZhiModel]!
    
    
    //定义一个点击我按钮
    var dianJiWo:UIButton?
    
    //定义一个textView,用于初始化一个键盘
    var jianPanTextView:UITextView?
    
    //定义一个分钟Label
    var fenZhongLabel:UILabel?
    
    //定义一个完成按钮
    var wanChengBtn:UIButton?
    
    //定义一个临时变量存储当switch开启和关闭时,代表的模式
    var linShiMoShiChangedValue:String?
    
    //定义一个临时变量存储用户输入的值
    var inputValue:String?
    
    override func viewDidLoad() {
        self.sheZhiMoShiAndTimeArray = []
        self.title = "设置"
        self.view.backgroundColor = UIColor(red: 232/255.0,green:232/255.0,blue:232/255.0,alpha:1)
        let leftBarButton = UIButton(frame:CGRect(x: 0,y: 0,width: 20,height: 20))
        leftBarButton.setBackgroundImage(UIImage(named: "fanhui"), for: UIControlState())
        leftBarButton.addTarget(self, action: #selector(backToPrevious), for: .touchUpInside)
        let leftBarButtonItem = UIBarButtonItem(customView: leftBarButton)
        self.navigationItem.leftBarButtonItems = [leftBarButtonItem]
        
        //初始化UITableView
        moShiLeiBieTableView = UITableView(frame:self.view.frame,style: .grouped)
        //设置代理和数据源
        self.moShiLeiBieTableView?.delegate = self
        self.moShiLeiBieTableView?.dataSource = self
        self.view.addSubview(moShiLeiBieTableView!)
        let cellNib = UINib(nibName: "SheZhiTableViewCell", bundle: nil)
        self.moShiLeiBieTableView!.register(cellNib, forCellReuseIdentifier: "moShiLeiBieTableViewCell")
        
        //初始化"点击我"按钮
        dianJiWo = UIButton(frame: CGRect(x: screenWidth/2-60, y: 230, width: 60, height: 60))
        dianJiWo?.backgroundColor = UIColor(red: 46/255.0,green:204/255.0,blue:113/255.0,alpha:1)
        dianJiWo?.setTitle("点击我", for: UIControlState())
        dianJiWo?.layer.cornerRadius = 30
        
        
        //初始化fenZhongLabel对象
        fenZhongLabel = UILabel(frame: CGRect(x: screenWidth/2, y: 230, width: 60 , height: 60))
        fenZhongLabel?.text = "分钟"
        fenZhongLabel?.font = UIFont.systemFont(ofSize: 15)
        fenZhongLabel?.textAlignment = .center
        fenZhongLabel?.layer.cornerRadius = 30
        fenZhongLabel?.clipsToBounds = true
        fenZhongLabel?.backgroundColor = UIColor(red: 46/255.0,green:204/255.0,blue:113/255.0,alpha:1)
        
        //初始化wanChengBtn按钮
        wanChengBtn = UIButton(frame: CGRect(x: 10, y: screenHeight-120, width: screenWidth-20 , height: 40))
        wanChengBtn?.backgroundColor = UIColor(red: 231/255,green: 76/255,blue: 60/255,alpha: 1)
        wanChengBtn?.layer.cornerRadius = 10
        wanChengBtn?.setTitle("完成", for: UIControlState())
        
        //创建表头标签
        let headerLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 30))
        headerLabel.textColor = UIColor.white
        headerLabel.numberOfLines = 0
        headerLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
        headerLabel.font = UIFont.italicSystemFont(ofSize: 20)
        self.moShiLeiBieTableView!.tableHeaderView = headerLabel
        
        dianJiWo?.addTarget(self, action: #selector(tanChuJianShuZiJianPan), for: .touchUpInside)
        wanChengBtn?.addTarget(self, action: #selector(wanChengSheZhi), for: .touchUpInside)
        self.view.addSubview(dianJiWo!)
        self.view.addSubview(fenZhongLabel!)
        self.view.addSubview(wanChengBtn!)
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    /*
        作者:张振东
        时间:2016-9-10
        功能:viewController即将显示时,添加键盘显示和隐藏事件
     */
    override func viewWillAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        
    }
    
   
    /*
        作者:张振东
        时间:2016-9-10
        功能:键盘弹出事件
     */
    func keyboardWillShow(_ notification:Notification){
        if ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil {
        //let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
        //let keyboardheight  = keyboardSize.height as CGFloat
        //let frame = self.nameInput.frame
        // frame.origin.y = frame.origin.y - keyboardheight
        //var offset = 156 as CGFloat
        let width = self.view.frame.size.width;
        let height = self.view.frame.size.height;
        let rect = CGRect(x: 0.0, y: -135,width: width,height: height);
        self.view.frame = rect
        }
    }
    
    /*
     作者:张振东
     时间:2016-9-10
     功能:键盘隐藏事件
     */
    func keyboardWillHide(_ notification:Notification){
        let width = self.view.frame.size.width;
        let height = self.view.frame.size.height;
        let rect = CGRect(x: 0.0, y: 0,width: width,height: height);
        self.view.frame = rect
    }

    
    /*
     作者:张振东
     时间:2016-9-10
     功能:返回几组
     */
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    /*
     作者:张振东
     时间:2016-9-10
     功能:每组显示几个cell
     */
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return moShiItems.count
    }
    
    /*
     作者:张振东
     时间:2016-9-10
     功能:定义tableViewcell的高度
     */
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
    /*
     作者:张振东
     时间:2016-9-10
     功能:行高
     */
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20;
    }
    
    /*
     作者:张振东
     时间:2016-9-10
     功能:尾高
     */
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 20;
    }
    
    /*
     作者:张振东
     时间:2016-9-10
     功能:显示行内容
     */
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view:UIView = UIView(frame:CGRect.zero)
        let label = UILabel(frame: CGRect(x: 10, y: 0, width: screenWidth, height: 20))
        label.textColor = UIColor(red: 0x8f/255.0,green:0x8f/255.0,blue:0x94/255.0,alpha:1.0)
        
        label.font = UIFont.systemFont(ofSize: 16)
        view.addSubview(label)
        
        return view
    }
    
    /*
     作者:张振东
     时间:2016-9-10
     功能:显示尾部内容
     */
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view:UIView = UIView(frame:CGRect.zero)
        
        let label = UILabel(frame: CGRect(x: 10, y: 0, width: screenWidth, height: 20))
        label.textColor = UIColor(red: 0x8f/255.0,green:0x8f/255.0,blue:0x94/255.0,alpha:1.0)
        label.backgroundColor = UIColor.clear
        view.addSubview(label)
       
        
        return view
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: SheZhiTableViewCell = tableView.dequeueReusableCell(withIdentifier: "moShiLeiBieTableViewCell") as!SheZhiTableViewCell!
//        if(indexPath.section == 0){
//            cell.textLabel?.text="头像";
//            cell.iconImageView = nil
//            
//        }else{
//            
//            cell.textLabel?.text = moShiItems[indexPath.row];
//            cell.moShiSwitcher?.setOn(true, animated: true)
//        }
//        cell.textLabel?.text = moShiItems[indexPath.row]
        
        if indexPath.row == 0{
            cell.iconImageView?.image = UIImage(named: "jishi")
            cell.moShiSwitcher?.isOn = true
            cell.moShiSwitcher?.tag = 0
            linShiMoShiChangedValue = "计时"
            
        }else{
            cell.iconImageView?.image = UIImage(named: "dingshi")
            cell.moShiSwitcher?.isOn = false
            cell.moShiSwitcher?.tag = 1
            
        }
        cell.moShiLeiBie?.text = moShiItems[indexPath.row]
        
        
        cell.moShiSwitcher?.addTarget(self, action: #selector(switchChange), for: .valueChanged)
        return cell
        
    }
    
    /*
     作者:张振东
     时间:2016-9-10
     功能:当UISwitch发生改变时,记录选中的值
     */
    func switchChange(_ sender:Any){
        let changedSwitch = sender as! UISwitch
        switch changedSwitch.tag  {
        case 0:
            if changedSwitch.isOn{
                linShiMoShiChangedValue = "计时"
                
            }
                break
            
        case 1:
            if changedSwitch.isOn{
                linShiMoShiChangedValue = "定时"
            }
                break
        default:
            print("")
        }
    }
    
    /*
     作者:张振东
     时间:2016-9-10
     功能:点击完成按钮,通过协议实现向上一个页面传值
     */
    func wanChengSheZhi(){
        print("将用户选择的值传递到上一个页面,并返回到上一个页面")
        print(linShiMoShiChangedValue as Any)
        print(inputValue as Any)
        if inputValue == nil{
            inputValue = "2"
        }
        delegate?.chuanDiMoShiAndFenZhong(linShiMoShiChangedValue!,xuanZhongFenZhongZhi: inputValue!)
        
        self.navigationController?.popViewController(animated: true)
    }
    
    //返回到上一个页面
    func backToPrevious(){
        self.navigationController?.popViewController(animated: true)
    }

    /*
     作者:张振东
     时间:2016-9-10
     功能:实现弹出键盘的功能
     */
    func tanChuJianShuZiJianPan(){
        print("我被点击了")
        
        //初始化键盘TextView
        jianPanTextView = UITextView(frame:CGRect(x: 0,y: screenHeight-140,width: screenWidth,height: 0))
        jianPanTextView?.delegate = self
        jianPanTextView?.becomeFirstResponder()
        jianPanTextView?.keyboardType = .numberPad
        
        self.view.addSubview(jianPanTextView!)
        
    }
    
    
    
    //获取点击的键盘中的值
    func textViewDidChange(_ textView: UITextView) {
        print(textView.text)
        inputValue = textView.text
        self.dianJiWo?.setTitle(inputValue, for: UIControlState())
        textView.resignFirstResponder()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
